//
//  RegisterViewController.m
//  XTXOneToOne
//
//  Created by Canny on 2018/10/29.
//  Copyright © 2018年 WK. All rights reserved.
//

#import "RegisterViewController.h"
#import "MCMainTabBarController.h"
#import "LoginViewController.h"


@interface RegisterViewController ()


@property (nonatomic,strong)  UIButton * receiveCheckNumButton;
@property (nonatomic,strong)  UIButton * registerBtn;
@property (nonatomic,strong)  UITextField * phoneTextField;
@property (nonatomic,strong)  UITextField * verificationCodeTextField;
@property (nonatomic,strong)  UITextField * passwordTextField;
@property (nonatomic,strong)  UITextField * passwordAgainTextField;


@end

@implementation RegisterViewController

- (void)viewDidLoad {
    
    [super viewDidLoad];
    
    [self setProperty];
    
    [self createUI];
    
}

-(void)viewWillAppear:(BOOL)animated{
    
    [super viewWillAppear:animated];
    
    [UIApplication sharedApplication].statusBarHidden = NO;
    
    self.navigationController.navigationBar.translucent = YES;
    
    self.navigationController.navigationBarHidden=YES;
}

#pragma mark=============setProperty=============
-(void)setProperty{
    
    self.view.backgroundColor=[UIColor whiteColor];
    
    [UIApplication sharedApplication].statusBarHidden = NO;
    
    self.navigationController.navigationBar.translucent = YES;
    
    self.navigationController.navigationBarHidden=YES;
}


-(void)createUI{
    
    
    UILabel *label = [[UILabel alloc] init];
    label.text = @"手机注册";
    label.font = [UIFont systemFontOfSize:30];
    label.textColor = RGB(30, 63, 89);
    [self.view addSubview:label];
    label.textAlignment = NSTextAlignmentLeft;
    
    [label mas_makeConstraints:^(MASConstraintMaker *make) {
        make.top.equalTo(self.view).offset(80);
        make.left.equalTo(self.view.mas_left).offset(20);
        make.width.equalTo(@(200));
        make.height.equalTo(@(40));
    }];

    
    
    UITextField * phoneTextField=[[UITextField alloc]init];
    _phoneTextField=phoneTextField;
    //    _phoneTextField.secureTextEntry = YES;
    _phoneTextField.tag=1001;
    [self.view addSubview:_phoneTextField];
    [self setTextField:_phoneTextField WithPlaceholder:@"请输入手机号码" and:UIKeyboardTypeDefault];
    [_phoneTextField mas_makeConstraints:^(MASConstraintMaker *make) {
        make.top.equalTo(label.mas_bottom).offset(60);
        make.left.equalTo(self.view.mas_left).offset(20);
        make.right.equalTo(self.view.mas_right).offset(-20);
        make.height.equalTo(@(30));
    }];
    
    UIView * line1 = [[UIView alloc]init];
    [self.view addSubview:line1];
    line1.backgroundColor=RGB(230, 234, 237);
    [line1 mas_makeConstraints:^(MASConstraintMaker *make) {
        make.top.equalTo(phoneTextField.mas_bottom).offset(10);
        make.left.equalTo(self.view.mas_left).offset(20);
        make.right.equalTo(self.view.mas_right).offset(-20);
        make.height.equalTo(@(0.8));
    }];
    
    UITextField * verificationCodeTextField=[[UITextField alloc]init];
    _verificationCodeTextField=verificationCodeTextField;
    _verificationCodeTextField.secureTextEntry = YES;
    _verificationCodeTextField.tag=1002;
    [self.view addSubview:_verificationCodeTextField];
    [self setTextField:_verificationCodeTextField WithPlaceholder:@"请输入验证码" and:UIKeyboardTypeDefault];
    [_verificationCodeTextField mas_makeConstraints:^(MASConstraintMaker *make) {
        make.top.equalTo(line1.mas_bottom).offset(20);
        make.left.equalTo(self.view.mas_left).offset(20);
        make.right.equalTo(self.view.mas_right).offset(-150);
        make.height.equalTo(@(30));
    }];
    
    _receiveCheckNumButton = [[UIButton alloc] init];
//    _receiveCheckNumButton.backgroundColor = [UIColor purpleColor];
    [_receiveCheckNumButton setTitle:@"发送验证码"forState:UIControlStateNormal];
    [_receiveCheckNumButton setTitleColor:RGB(117, 160, 221) forState:UIControlStateNormal];
    _receiveCheckNumButton.titleLabel.font = [UIFont systemFontOfSize:15];
//    _receiveCheckNumButton.layer.cornerRadius =5;
//    _receiveCheckNumButton.layer.masksToBounds =YES;
//    _receiveCheckNumButton.alpha =0.3;
    [self.view addSubview:_receiveCheckNumButton];
    [_receiveCheckNumButton mas_makeConstraints:^(MASConstraintMaker *make) {
        make.centerY.equalTo(self.verificationCodeTextField.mas_centerY).offset(0);
        make.width.equalTo(@(100));
        make.right.equalTo(self.view.mas_right).offset(-20);
        make.height.equalTo(@(30));
    }];

    [_receiveCheckNumButton addTarget:self action:@selector(actionReceiveCheckNumButton) forControlEvents:UIControlEventTouchUpInside];

    
    UIView * line2 = [[UIView alloc]init];
    [self.view addSubview:line2];
    line2.backgroundColor=RGB(230, 234, 237);
    [line2 mas_makeConstraints:^(MASConstraintMaker *make) {
        make.top.equalTo(verificationCodeTextField.mas_bottom).offset(10);
        make.left.equalTo(self.view.mas_left).offset(20);
        make.right.equalTo(self.view.mas_right).offset(-20);
        make.height.equalTo(@(0.8));
    }];
    
    
    UITextField * passwordTextField=[[UITextField alloc]init];
    _passwordTextField=passwordTextField;
    _passwordTextField.secureTextEntry = YES;
    _passwordTextField.tag=1003;
    [self.view addSubview:_passwordTextField];
    [self setTextField:_passwordTextField WithPlaceholder:@"请输入密码" and:UIKeyboardTypeDefault];
    [_passwordTextField mas_makeConstraints:^(MASConstraintMaker *make) {
        make.top.equalTo(line2.mas_bottom).offset(20);
        make.left.equalTo(self.view.mas_left).offset(20);
        make.right.equalTo(self.view.mas_right).offset(-20);
        make.height.equalTo(@(30));
    }];
    
    UIView * line3 = [[UIView alloc]init];
    [self.view addSubview:line3];
    line3.backgroundColor=RGB(230, 234, 237);
    [line3 mas_makeConstraints:^(MASConstraintMaker *make) {
        make.top.equalTo(passwordTextField.mas_bottom).offset(10);
        make.left.equalTo(self.view.mas_left).offset(20);
        make.right.equalTo(self.view.mas_right).offset(-20);
        make.height.equalTo(@(0.8));
    }];
    
    
    UITextField * passwordAgainTextField=[[UITextField alloc]init];
    _passwordAgainTextField=passwordAgainTextField;
    _passwordAgainTextField.secureTextEntry = YES;
    _passwordAgainTextField.tag=1004;
    [self.view addSubview:_passwordAgainTextField];
    [self setTextField:_passwordAgainTextField WithPlaceholder:@"请再次输入密码" and:UIKeyboardTypeDefault];
    [_passwordAgainTextField mas_makeConstraints:^(MASConstraintMaker *make) {
        make.top.equalTo(line3.mas_bottom).offset(20);
        make.left.equalTo(self.view.mas_left).offset(20);
        make.right.equalTo(self.view.mas_right).offset(-20);
        make.height.equalTo(@(30));
    }];
    
    UIView * line4 = [[UIView alloc]init];
    [self.view addSubview:line4];
    line4.backgroundColor=RGB(230, 234, 237);
    [line4 mas_makeConstraints:^(MASConstraintMaker *make) {
        make.top.equalTo(passwordAgainTextField.mas_bottom).offset(10);
        make.left.equalTo(self.view.mas_left).offset(20);
        make.right.equalTo(self.view.mas_right).offset(-20);
        make.height.equalTo(@(0.8));
    }];
    
    UIButton * registerBtn = [UIButton buttonWithType:UIButtonTypeCustom];
    [registerBtn setTitle:@"确认注册" forState:UIControlStateNormal];
    [registerBtn setTitleColor:RGB(255, 255, 255) forState:UIControlStateNormal];
    [registerBtn addTarget:self action:@selector(btnClickAction:) forControlEvents:UIControlEventTouchUpInside];
    [self.view addSubview:registerBtn];
    registerBtn.backgroundColor=RGB(206, 217, 222);
    registerBtn.tag=9001;
    registerBtn.contentHorizontalAlignment = UIControlContentHorizontalAlignmentCenter;
    registerBtn.titleLabel.font=[UIFont systemFontOfSize:15];
    _registerBtn= registerBtn;
    [registerBtn mas_makeConstraints:^(MASConstraintMaker *make) {
        make.top.equalTo(line4.mas_bottom).offset(75);
        make.left.equalTo(label);
        make.right.equalTo(self.view.mas_right).offset(-20);
        make.height.equalTo(@(50));
    }];
    

    
   
    UIButton * loginBtn = [UIButton buttonWithType:UIButtonTypeCustom];
    [loginBtn setTitle:@"登录" forState:UIControlStateNormal];
    [loginBtn setTitleColor:RGB(99, 140, 220) forState:UIControlStateNormal];
    [loginBtn addTarget:self action:@selector(btnClickAction:) forControlEvents:UIControlEventTouchUpInside];
    [self.view addSubview:loginBtn];
    //    registerBtn.backgroundColor=RGB(206, 217, 222);
    loginBtn.tag=9003;
    loginBtn.contentHorizontalAlignment = UIControlContentHorizontalAlignmentCenter;
    loginBtn.titleLabel.font=[UIFont systemFontOfSize:15];
    [loginBtn mas_makeConstraints:^(MASConstraintMaker *make) {
        
        make.top.equalTo(self.view.mas_top).offset(TopBackButtonHeight);
        make.right.equalTo(self.view.mas_right).offset(-20);
        make.height.equalTo(@(50));
        make.width.equalTo(@(50));
    }];
    
   
    UIView *view1 = [[UIView alloc] init];
    view1.backgroundColor=[UIColor whiteColor];
    [self.view addSubview:view1];
    //边框宽
    view1.layer.borderWidth = 2;
    //边框颜色
    view1.layer.borderColor = [RGB(206, 217, 222) CGColor];
    [view1 mas_makeConstraints:^(MASConstraintMaker *make) {
        make.top.equalTo(line4.mas_bottom).offset(30);
        make.left.equalTo(self.view.mas_left).offset(20);
        
        make.height.equalTo(@(20));
        make.width.equalTo(@(20));
    }];
    
    UIView * view2 = [[UIView alloc]init];
    view2.backgroundColor=RGB(117, 160, 221);
    [view1 addSubview:view2];
    [view2 mas_makeConstraints:^(MASConstraintMaker *make) {
        make.centerX.equalTo(view1.mas_centerX);
      make.centerY.equalTo(view1.mas_centerY);
        
        make.height.equalTo(@(10));
        make.width.equalTo(@(10));
    }];
    
    UILabel *tylabel = [[UILabel alloc] init];
    tylabel.text = @"同意《用户服务条款与用户隐私协议》";
    tylabel.font = [UIFont systemFontOfSize:14];
    tylabel.textColor = RGB(197, 207, 213);
    [self.view addSubview:tylabel];
    [tylabel mas_makeConstraints:^(MASConstraintMaker *make) {
        make.left.equalTo(view1.mas_right).offset(20);
        make.centerY.equalTo(view1.mas_centerY);
        make.height.equalTo(@(10));
        make.width.equalTo(@(300));
    }];
    
    UITapGestureRecognizer *singleTapGesture = [[UITapGestureRecognizer alloc] initWithTarget:self action:@selector(closeKeyboard:)];
    singleTapGesture.numberOfTapsRequired = 1;
    singleTapGesture.cancelsTouchesInView = NO;
    [self.view  addGestureRecognizer:singleTapGesture];
    
}


#pragma mark - gesture actions
- (void)closeKeyboard:(UITapGestureRecognizer *)recognizer {
    
    [self.view endEditing:YES];
    //    [self.viewPop hiden];
}

-(void)setTextField:(UITextField*)textField WithPlaceholder:(NSString *)placeholder and:(UIKeyboardType)type  {

    textField.placeholder=placeholder;
    textField.borderStyle = UITextBorderStyleNone;
    textField.backgroundColor=[UIColor clearColor];
    textField.font = [UIFont systemFontOfSize:15];
    textField.textColor = RGB(40, 40, 40);
    textField.textAlignment = NSTextAlignmentLeft;
    textField.returnKeyType = UIReturnKeyDone;
    textField.keyboardType = type;
    [textField setValue:RGB(190, 190, 190) forKeyPath:@"_placeholderLabel.textColor"];
    [textField setValue:[UIFont systemFontOfSize:14] forKeyPath:@"_placeholderLabel.font"];
    [textField addTarget:self action:@selector(textFieldDidChange:) forControlEvents:(UIControlEventEditingChanged)];
    
}

-(void)textFieldDidChange:(UITextField *)textField{
    textField.text= [textField.text stringByReplacingOccurrencesOfString:@" " withString:@""];
   
    if (_phoneTextField.text.length>1&&_verificationCodeTextField.text.length>1&&_passwordTextField.text.length>1&&_passwordAgainTextField.text.length>1) {
        _registerBtn.backgroundColor=ThemeColor;
        
    }else{
        _registerBtn.backgroundColor=RGB(206, 217, 222);
        
    }
    if (textField.tag==1001) {
        
    }else if(textField.tag==1002){
        
    }
}

-(void)btnClickAction:(UIButton *)btn{
    
    
    //立即注册
    if (btn.tag==9001){
        if (_phoneTextField.text.length<1) {
            [HUD showMessage:@"请输入手机号！"];
            return;
        }
        if (_verificationCodeTextField.text.length<1) {
            [HUD showMessage:@"请输入验证码！"];
            return;
        }
        if (_passwordTextField.text.length<1) {
            [HUD showMessage:@"请输入密码！"];
            return;
        }
        if (_passwordAgainTextField.text.length<1) {
            [HUD showMessage:@"请输入密码！"];
            return;
        }
        if (![_passwordTextField.text isEqualToString:_passwordAgainTextField.text]) {
            [HUD showMessage:@"两次输入的密码不一致！"];
            return;
        }
        
        
        NSString * URL = [NSString stringWithFormat:@"%@user/register",DEFAULTSEVERBASEURL];

        NSDictionary * Dic = @{@"phone":_phoneTextField.text,@"code":_verificationCodeTextField.text,@"password":_passwordTextField.text,@"source":@"2"};
        __weak __typeof(self)wself = self;

        [MOLoadHttpsData PostHttpDataWithUrlStr:URL Dic:Dic SuccessBlock:^(id  _Nonnull responseObject) {
            NSDictionary * dic = responseObject;
            NSString * code = [NSString stringWithFormat:@"%@",dic[@"code"]];
            if ([code isEqualToString:@"0"]) {

                [HUD showMessage:dic[@"msg"]];
                //跳转登录
                [wself.navigationController popViewControllerAnimated:NO];
            }else{
                [HUD showErrorMessage:dic[@"msg"]];
            }
            
        } FailureBlock:^(id  _Nonnull error) {
            
        }];
        
    }else if(btn.tag==9002){
        
   
        //跳转登录
    }else if (btn.tag==9003){
//        [[[UIApplication sharedApplication] keyWindow] setRootViewController:[[LoginViewController alloc] init]];
        [self.navigationController popViewControllerAnimated:YES];
        
    }
    
}

//-(void)goBackAction{
//    [super goBackAction];
//    [self.navigationController popViewControllerAnimated:YES];
//    
//}

#pragma mark-获取验证码倒计时
- (void)actionReceiveCheckNumButton{
    
    __weak __typeof(self)wself = self;

    if (_phoneTextField.text.length<1) {
        [HUD showErrorMessage:@"请输入手机号！"];
        return;
    }
    NSString * URL = [NSString stringWithFormat:@"%@verify/sms",DEFAULTSEVERBASEURL];
    
    [MOLoadHttpsData PostHttpDataWithUrlStr:URL Dic:@{@"action":@"register",@"phone":_phoneTextField.text} SuccessBlock:^(id  _Nonnull responseObject) {
        NSDictionary * dic = responseObject;
        NSString * code = [NSString stringWithFormat:@"%@",dic[@"code"]];
        if ([code isEqualToString:@"0"]) {
            [wself startTimer];
        }else{
            [HUD showErrorMessage:dic[@"msg"]];
        }
        
    } FailureBlock:^(id  _Nonnull error) {
        
    }];
    
}

-(void)startTimer{
    
    __weak __typeof(self)wself = self;
    
    __block int timeout=60;//倒计时时间
    dispatch_queue_t queue =dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT,0);
    dispatch_source_t _timer = dispatch_source_create(DISPATCH_SOURCE_TYPE_TIMER,0, 0,queue);
    dispatch_source_set_timer(_timer,dispatch_walltime(NULL,0),1.0*NSEC_PER_SEC,0); //每秒执行
    dispatch_source_set_event_handler(_timer, ^{
        if(timeout<=0){//倒计时结束,关闭
            dispatch_source_cancel(_timer);
            dispatch_async(dispatch_get_main_queue(), ^{
                //设置界面的按钮显示根据自己需求设置
                [wself.receiveCheckNumButton setTitle:@"发送验证码"forState:UIControlStateNormal];
                wself.receiveCheckNumButton.userInteractionEnabled =YES;
                //                wself.receiveCheckNumButton.backgroundColor = [UIColor purpleColor];
            });
        }else{
            int seconds = timeout;
            NSString *strTime = [NSString stringWithFormat:@"%.2d", seconds];
            dispatch_async(dispatch_get_main_queue(), ^{
                //让按钮变为不可点击的灰色
                //                wself.receiveCheckNumButton.backgroundColor = [UIColor grayColor];
                wself.receiveCheckNumButton.userInteractionEnabled =NO;
                //设置界面的按钮显示根据自己需求设置
                [UIView beginAnimations:nil context:nil];
                [UIView setAnimationDuration:1];
                [wself.receiveCheckNumButton setTitle:[NSString stringWithFormat:@"%@秒后重发",strTime]forState:UIControlStateNormal];
                [UIView commitAnimations];
            });
            timeout--;
        }
    });
    dispatch_resume(_timer);
}

@end
